﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Interactivity;
using System.Collections;
using System.Collections.Generic;
using System.Windows.Data;
using System.Linq;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
namespace Phone.Framework.Behaviors
{
    public class MediaPlayBehavior : Behavior<PhoneApplicationPage>
    {

        private MediaElement mediaElement;

        protected override void OnAttached()
        {
            mediaElement = new MediaElement() { AutoPlay=false };
            mediaElement.MediaOpened += new RoutedEventHandler(mediaElement_MediaOpened);
            mediaElement.MediaEnded += new RoutedEventHandler(mediaElement_MediaEnded);
            var panel = AssociatedObject.Content as Panel;
            panel.Children.Add(mediaElement);
            base.OnAttached();
        }

        void mediaElement_MediaEnded(object sender, RoutedEventArgs e)
        {
            mediaElement.Source = null;
            SourceUrl = string.Empty;
            IsCanPlay = true;
            if (_action != null)
                _action();
        }

        void mediaElement_MediaOpened(object sender, RoutedEventArgs e)
        {
            mediaElement.Play();
        }

        public bool IsCanPlay
        {
            get { return (bool)GetValue(IsCanPlayProperty); }
            set { SetValue(IsCanPlayProperty, value); }
        }

        public static readonly DependencyProperty IsCanPlayProperty =
            DependencyProperty.Register("IsCanPlay", typeof(bool), typeof(MediaPlayBehavior), 
            new PropertyMetadata(true));

        public string SourceUrl
        {
            get { return (string)GetValue(SourceUrlProperty); }
            set { SetValue(SourceUrlProperty, value); }
        }

        private void SetSource()
        {
            if (!string.IsNullOrEmpty(SourceUrl))
            {
                IsCanPlay = false;
                mediaElement.Source = new Uri(SourceUrl, UriKind.RelativeOrAbsolute);
                mediaElement.Volume = 1;
                mediaElement.Position = new TimeSpan(0);
            }
        }

        public static readonly DependencyProperty SourceUrlProperty =
            DependencyProperty.Register("SourceUrl", typeof(string), typeof(MediaPlayBehavior),
            new PropertyMetadata(string.Empty, (sender, arg) => {
                var behavior = sender as MediaPlayBehavior;
                behavior.SetSource();
            }));


        private Action _action;
        public void Play(string soruceUrl,Action action)
        {
            SourceUrl = soruceUrl;
            _action=action;
        }

    }
}